﻿
using LS.Nc6.Web.Entry.Areas.Cms.Models;
using Org.BouncyCastle.Crypto;
using SixLabors.ImageSharp;
using System.Security.Policy;
using System.Threading.Channels;

namespace LS.Nc6.Web.Entry.Areas.Cms.Controllers
{
    /// <summary>
    /// 内容表
    /// </summary>
    [Route("[area]/[controller]/[action]")]
    [Area("Cms")]
    [ApiDescriptionSettings("Default")]
    public class ContentController : BaseAdminController
    {
        #region CmsContentController
        private readonly ICmsContentCheckService _contentCheckService;
        private readonly ICmsContentService _contentService;
        private readonly ICmsContentGroupService _contentGroupService;
        private readonly ICmsContentTagService _contentTagService;
        private readonly ICmsTablestyleService _tablestyleService;
        private readonly ICmsChannelService _channelService;
        private readonly ICache _cache;
        public ContentController(ICmsContentCheckService contentCheckService, ICmsContentService contentService,
            ICmsContentGroupService contentGroupService,
            ICmsContentTagService contentTagService,
            ICmsTablestyleService tablestyleService,
            ICmsChannelService channelService,
            IOptions<CacheOptions> cacheOptions, Func<string, ISingleton, object> resolveNamed)
            : base(cacheOptions, resolveNamed)
        {
            _contentCheckService = contentCheckService;
            _contentTagService = contentTagService;
            _contentService = contentService;
            _contentGroupService = contentGroupService;
            _tablestyleService = tablestyleService;
            _channelService = channelService;
            _cache = resolveNamed(cacheOptions.Value.CacheType.ToString(), default) as ICache;
        }
        #endregion

        #region 页面
        public ActionResult Index()
        {
            SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_SELECT, UserInfo.ID.ToString());

            //ViewBag.AuthUpdate = SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString(), false) ? 1 : 0;
            //ViewBag.AuthDelete = SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_DELETE, UserInfo.ID.ToString(), false) ? 1 : 0;

            //ViewBag.AuthAll = (ViewBag.AuthUpdate == 0 && ViewBag.AuthDelete == 0) ? 1 : 0;
            return View();
        }
        public async Task<ActionResult> Create(long id)
        {
            SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_SELECT, UserInfo.ID.ToString());

            var channelModel = await _channelService.GetByIdAsync(id);
            if (channelModel == null)
            {
                return ErrorCustomMsg(ResponseHelper.NONEXISTENT);
            }
            var model = new CmsContentEntity();
            model.ChannelId = id;
            model.ExtendValues = "{}";

            #region   分组
            List<Hashtable> hsContentGroup = new List<Hashtable>();
            var contentGroups = await _contentGroupService.List(a => true, a => a.Taxis);
            foreach (var item in contentGroups)
            {
                Hashtable hs = new Hashtable();
                hs.Add("GroupName", item.GroupName);
                hs.Add("Checked", "0");
                hsContentGroup.Add(hs);
            }
            ViewBag.GroupNamesList = hsContentGroup;
            #endregion

            #region   标签
            List<Hashtable> hsContentTag = new List<Hashtable>();
            var contentTags = await _contentTagService.List(a => true, a => a.UseNum);
            foreach (var item in contentTags)
            {
                Hashtable hs = new Hashtable();
                hs.Add("TagName", item.TagName);
                hs.Add("Checked", "0");
                hsContentTag.Add(hs);
            }
            ViewBag.TagNamesList = hsContentTag;
            #endregion

            var defaulttableStyle = CmsHelper.GetDefaultContentTableStyle();

            bool isSystemField = false;
            string parentpath = string.IsNullOrEmpty(channelModel.ParentsPath) ? model.ChannelId.ToString() : channelModel.ParentsPath + "," + model.ChannelId.ToString();
            var tablestylelist = await _tablestyleService.List(a => parentpath.GetStringToLongArryNoNull().Contains(a.RelatedIdentity.Value), a => a.Taxis);

            List<TablestyleInput> listfield = new List<TablestyleInput>();

            Dictionary<string, List<InputStyleRule>> ruleList = new Dictionary<string, List<InputStyleRule>>();

            if (tablestylelist.Count > 0)
            {
                foreach (var item in tablestylelist)
                {
                    if (!isSystemField && item.BuiltIn == 1)
                    {
                        isSystemField = true;
                    }
                    var inputStyleRule = new List<InputStyleRule>();
                    var inputStyleItemValue = new List<InputStyleItemVuale>();
                    if (!string.IsNullOrEmpty(item.ExtendValues))
                    {
                        InputStyleItem inputStyleItem = JsonSerializer.Deserialize<InputStyleItem>(item.ExtendValues, CommonMethodHelper.MyHtmlJsonOptions);

                        if (!string.IsNullOrEmpty(inputStyleItem.RuleValues))
                        {
                            var JObjectNode = JsonNode.Parse(inputStyleItem.RuleValues);
                            JsonArray JArray = JObjectNode.AsArray()!;

                            List<InputStyleRule> itemrule = new List<InputStyleRule>();
                            foreach (var ist in JArray)
                            {
                                var JsonObject = ist.AsObject()!;

                                var rulemodel = new InputStyleRule
                                {
                                    Type = JsonObject["type"].ToString(),
                                    Message = JsonObject["message"].ToString(),
                                    Value = JsonObject["value"].ToString()
                                };
                                inputStyleRule.Add(rulemodel);
                                if (item.BuiltIn == 0 && "Regex" == rulemodel.Type)
                                {
                                    itemrule.Add(rulemodel);
                                }

                            }
                            ruleList.Add(item.AttributeName, itemrule);
                        }

                        if (!string.IsNullOrEmpty(inputStyleItem.ItemValues))
                        {
                            var JObjectNodeItem = JsonNode.Parse(inputStyleItem.ItemValues);
                            JsonArray JArrayitem = JObjectNodeItem.AsArray()!;

                            foreach (var ist in JArrayitem)
                            {
                                var JsonObject = ist.AsObject()!;

                                inputStyleItemValue.Add(new InputStyleItemVuale
                                {
                                    Label = JsonObject["label"].ToString(),
                                    Selected = JsonObject["selected"].ToString(),
                                    Value = JsonObject["value"].ToString()
                                });
                            }
                        }
                    }

                    var tinput = new TablestyleInput
                    {
                        Id = item.Id,
                        RelatedIdentity = item.RelatedIdentity,
                        AttributeName = item.AttributeName,
                        DisplayName = item.DisplayName,
                        Taxis = item.Taxis,
                        HelpText = item.HelpText,
                        List = 0,
                        InputType = item.InputType,
                        DefaultValue = item.DefaultValue,
                        ExtendRuleValues = inputStyleRule,
                        ExtendItemValues = inputStyleItemValue
                    };
                    listfield.Add(tinput);
                }
            }

            if (!isSystemField)
            {
                listfield.AddRange(defaulttableStyle);
            }
            listfield.Sort((a, b) => {
                if (a.Taxis > b.Taxis)
                {
                    return 1;
                }
                else if (a.Taxis == b.Taxis)
                {
                    return 0;
                }
                else
                {
                    return -1;
                }
            });
            ViewBag.FieldList = listfield;

            //富文本框
            List<string> textEditor = listfield.Where(a => a.InputType == InputType.TextEditor.ToString()).Select(a => a.AttributeName).ToList();

            ViewBag.TextEditor = JsonSerializer.Serialize(textEditor, CommonMethodHelper.MyJsonOptions);

            //video
            List<string> textVideo = listfield.Where(a => a.InputType == InputType.Video.ToString()).Select(a => a.AttributeName).ToList();
            ViewBag.TextVideo = JsonSerializer.Serialize(textVideo, CommonMethodHelper.MyJsonOptions);

            //image
            List<string> textImage = listfield.Where(a => a.InputType == InputType.Image.ToString()).Select(a => a.AttributeName).ToList();
            ViewBag.TextImage = JsonSerializer.Serialize(textImage, CommonMethodHelper.MyJsonOptions);

            //file
            List<string> textFile = listfield.Where(a => a.InputType == InputType.File.ToString()).Select(a => a.AttributeName).ToList();
            ViewBag.TextFile = JsonSerializer.Serialize(textFile, CommonMethodHelper.MyJsonOptions);

            //data
            List<string> textData = listfield.Where(a => a.InputType == InputType.Date.ToString()).Select(a => a.AttributeName).ToList();
            ViewBag.TextData = JsonSerializer.Serialize(textData, CommonMethodHelper.MyJsonOptions);

            //datatime
            List<string> textDataTime = listfield.Where(a => a.InputType == InputType.DateTime.ToString()).Select(a => a.AttributeName).ToList();
            ViewBag.TextDataTime = JsonSerializer.Serialize(textDataTime, CommonMethodHelper.MyJsonOptions);

            //chckbox
            List<string> textCheckbox = listfield.Where(a => a.InputType == InputType.CheckBox.ToString()).Select(a => a.AttributeName).ToList();
            ViewBag.TextCheckbox = JsonSerializer.Serialize(textCheckbox, CommonMethodHelper.MyJsonOptions);

            //multiple
            List<string> textMultiple = listfield.Where(a => a.InputType == InputType.SelectMultiple.ToString()).Select(a => a.AttributeName).ToList();
            ViewBag.TextMultiple = JsonSerializer.Serialize(textMultiple, CommonMethodHelper.MyJsonOptions);

            //验证规则


            ViewBag.RuleList = JsonSerializer.Serialize(ruleList, CommonMethodHelper.MyJsonOptions);

            //扩展属性值


            model.Checked = 3;
            return View("Edit", model);
        }
        public async Task<ActionResult> Edit(long id)
        {
            SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString());
            var model = await _contentService.GetByIdAsync(id);
            if (model == null)
            {
                return ErrorCustomMsg(ResponseHelper.NONEXISTENT);
            }
            var channelModel = await _channelService.GetByIdAsync(model.ChannelId);
            #region 分组
            var contentGroups = await _contentGroupService.List(a => true, a => a.Taxis);
            List<Hashtable> hsContentGroup = new List<Hashtable>();
            var grouplist = CommonUtil.GetStringListNoNull(model.GroupNameCollection);
            foreach (var item in contentGroups)
            {
                Hashtable hs = new Hashtable();
                hs.Add("GroupName", item.GroupName);
                hs.Add("Checked", RequestHelper.Contains<string>(grouplist, item.GroupName.ToString()) ? "1" : "0");
                hsContentGroup.Add(hs);
            }
            ViewBag.GroupNamesList = hsContentGroup;

            #endregion

            #region   标签
            List<Hashtable> hsContentTag = new List<Hashtable>();
            var contentTags = await _contentTagService.List(a => true, a => a.UseNum);
            var taglist = CommonUtil.GetStringListNoNull(model.Tags);
            foreach (var item in contentTags)
            {
                Hashtable hs = new Hashtable();
                hs.Add("TagName", item.TagName);
                hs.Add("Checked", RequestHelper.Contains<string>(taglist, item.TagName.ToString()) ? "1" : "0");
                hsContentTag.Add(hs);
            }
            ViewBag.TagNamesList = hsContentTag;
            #endregion

            #region 解析扩展
            JsonObject jsonObjectExtend = null;

            if (!string.IsNullOrEmpty(model.ExtendValues))
            {
                var JObjectNode = JsonNode.Parse(model.ExtendValues);
                jsonObjectExtend = JObjectNode.AsObject()!;

            }
            #endregion

            var defaulttableStyle = CmsHelper.GetDefaultContentTableStyle();

            bool isSystemField = false;
            string parentpath = string.IsNullOrEmpty(channelModel.ParentsPath) ? model.ChannelId.ToString() : channelModel.ParentsPath + "," + model.ChannelId.ToString();
            var tablestylelist = await _tablestyleService.List(a => parentpath.GetStringToLongArryNoNull().Contains(a.RelatedIdentity.Value), a => a.Taxis);

            List<TablestyleInput> listfield = new List<TablestyleInput>();
            Dictionary<string, List<InputStyleRule>> ruleList = new Dictionary<string, List<InputStyleRule>>();
            if (tablestylelist.Count > 0)
            {
                foreach (var item in tablestylelist)
                {
                    if (!isSystemField && item.BuiltIn == 1)
                    {
                        isSystemField = true;
                    }

                    var inputStyleRule = new List<InputStyleRule>();
                    var inputStyleItemValue = new List<InputStyleItemVuale>();
                    if (!string.IsNullOrEmpty(item.ExtendValues))
                    {
                        InputStyleItem inputStyleItem = JsonSerializer.Deserialize<InputStyleItem>(item.ExtendValues, CommonMethodHelper.MyHtmlJsonOptions);
                        if (!string.IsNullOrEmpty(inputStyleItem.RuleValues))
                        {
                            var JObjectNode = JsonNode.Parse(inputStyleItem.RuleValues);
                            JsonArray JArray = JObjectNode.AsArray()!;
                            List<InputStyleRule> itemrule = new List<InputStyleRule>();
                            foreach (var ist in JArray)
                            {
                                var JsonObject = ist.AsObject()!;
                                var rulemodel = new InputStyleRule
                                {
                                    Type = JsonObject["type"].ToString(),
                                    Message = JsonObject["message"].ToString(),
                                    Value = JsonObject["value"].ToString()
                                };
                                inputStyleRule.Add(rulemodel);
                                if (item.BuiltIn == 0 && "Regex" == rulemodel.Type)
                                {
                                    itemrule.Add(rulemodel);
                                }
                            }
                            ruleList.Add(item.AttributeName, itemrule);
                        }

                        if (!string.IsNullOrEmpty(inputStyleItem.ItemValues))
                        {
                            var JObjectNodeItem = JsonNode.Parse(inputStyleItem.ItemValues);
                            JsonArray JArrayitem = JObjectNodeItem.AsArray()!;

                            foreach (var ist in JArrayitem)
                            {
                                var JsonObject = ist.AsObject()!;
                                var itemValueModel = new InputStyleItemVuale
                                {
                                    Label = JsonObject["label"].ToString(),
                                    Selected = JsonObject["selected"].ToString(),
                                    Value = JsonObject["value"].ToString()

                                };
                                if (item.InputType == "CheckBox" || item.InputType == "Radio" || item.InputType == "SelectOne" || item.InputType == "SelectMultiple")
                                {
                                    if (jsonObjectExtend != null && jsonObjectExtend.ContainsKey(item.AttributeName))
                                    {
                                        itemValueModel.Selected = jsonObjectExtend[item.AttributeName].ToString().GetStringArrayNoNull().Contains(itemValueModel.Value) ? "1" : "0";
                                    }
                                    else
                                    {
                                        itemValueModel.Selected = "0";
                                    }
                                }
                                inputStyleItemValue.Add(itemValueModel);
                            }
                        }
                    }
                    string defaultValue = string.Empty;
                    if (CmsHelper.GetAttributteList().Contains(item.AttributeName))
                    {
                        defaultValue = CommonMethodHelper.GetModelProperty(model, item.AttributeName);
                    }
                    else
                    {
                        defaultValue = jsonObjectExtend != null && jsonObjectExtend.ContainsKey(item.AttributeName) ? jsonObjectExtend[item.AttributeName].ToString() : string.Empty;
                    }

                    var tinput = new TablestyleInput
                    {
                        Id = item.Id,
                        RelatedIdentity = item.RelatedIdentity,
                        AttributeName = item.AttributeName,
                        DisplayName = item.DisplayName,
                        Taxis = item.Taxis,
                        HelpText = item.HelpText,
                        List = 0,
                        InputType = item.InputType,
                        DefaultValue = defaultValue,
                        //DefaultValue =CmsHelper.GetAttributteList().Contains(item.AttributeName)? CommonMethodHelper. GetModelProperty(model, item.AttributeName) : jsonObjectExtend!=null ? jsonObjectExtend[item.AttributeName].ToString():string.Empty,
                        ExtendRuleValues = inputStyleRule,
                        ExtendItemValues = inputStyleItemValue
                    };
                    listfield.Add(tinput);
                }
            }

            if (!isSystemField)
            {
                foreach (var item in defaulttableStyle)
                {
                    item.DefaultValue = CommonMethodHelper.GetModelProperty(model, item.AttributeName);
                }
                listfield.AddRange(defaulttableStyle);
            }
            listfield.Sort((a, b) => {
                if (a.Taxis > b.Taxis)
                {
                    return 1;
                }
                else if (a.Taxis == b.Taxis)
                {
                    return 0;
                }
                else
                {
                    return -1;
                }
            });
            ViewBag.FieldList = listfield;

            //富文本框
            List<string> textEditor = listfield.Where(a => a.InputType == InputType.TextEditor.ToString()).Select(a => a.AttributeName).ToList();

            ViewBag.TextEditor = JsonSerializer.Serialize(textEditor, CommonMethodHelper.MyJsonOptions);

            //video
            List<string> textVideo = listfield.Where(a => a.InputType == InputType.Video.ToString()).Select(a => a.AttributeName).ToList();
            ViewBag.TextVideo = JsonSerializer.Serialize(textVideo, CommonMethodHelper.MyJsonOptions);

            //image
            List<string> textImage = listfield.Where(a => a.InputType == InputType.Image.ToString()).Select(a => a.AttributeName).ToList();
            ViewBag.TextImage = JsonSerializer.Serialize(textImage, CommonMethodHelper.MyJsonOptions);

            //file
            List<string> textFile = listfield.Where(a => a.InputType == InputType.File.ToString()).Select(a => a.AttributeName).ToList();
            ViewBag.TextFile = JsonSerializer.Serialize(textFile, CommonMethodHelper.MyJsonOptions);

            //data
            List<string> textData = listfield.Where(a => a.InputType == InputType.Date.ToString()).Select(a => a.AttributeName).ToList();
            ViewBag.TextData = JsonSerializer.Serialize(textData, CommonMethodHelper.MyJsonOptions);

            //datatime
            List<string> textDataTime = listfield.Where(a => a.InputType == InputType.DateTime.ToString()).Select(a => a.AttributeName).ToList();
            ViewBag.TextDataTime = JsonSerializer.Serialize(textDataTime, CommonMethodHelper.MyJsonOptions);

            //chckbox
            List<string> textCheckbox = listfield.Where(a => a.InputType == InputType.CheckBox.ToString()).Select(a => a.AttributeName).ToList();
            ViewBag.TextCheckbox = JsonSerializer.Serialize(textCheckbox, CommonMethodHelper.MyJsonOptions);

            //multiple
            List<string> textMultiple = listfield.Where(a => a.InputType == InputType.SelectMultiple.ToString()).Select(a => a.AttributeName).ToList();
            ViewBag.TextMultiple = JsonSerializer.Serialize(textMultiple, CommonMethodHelper.MyJsonOptions);

            //验证规则
            var rules = listfield.Where(a => a.ExtendRuleValues != null && a.ExtendRuleValues.Count > 0).ToList();

            ViewBag.RuleList = JsonSerializer.Serialize(rules, CommonMethodHelper.MyJsonOptions);

            model.ExtendValues = string.IsNullOrEmpty(model.ExtendValues) ? "{}" : model.ExtendValues;

            return View(model);
        }

        public ActionResult Search(int id)
        {
            SysPower(SysMenuConstant.MENU_CMS_NEWS_NRSS, SysMenuConstant.FUN_SELECT, UserInfo.ID.ToString());
            return View();
        }

        public ActionResult Attr(string  id)
        {
            SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_ATTRIBUTES, UserInfo.ID.ToString());
            ViewBag.Ids = id;
            return View();
        }

        public ActionResult Taxis(string id)
        {
            SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_TAXIS, UserInfo.ID.ToString());
            ViewBag.Ids = id;
            return View();
        }
        public async  Task<ActionResult> Translate(string id)
        {
            ViewBag.Ids = id;
            SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_COPY, UserInfo.ID.ToString());
            var contentList = await _contentService.List(a => id.GetStringToLongArryNoNull().Contains(a.Id), a => a.Id, a => new {
                a.Id,
                a.Title,
                a.CreateDate,
                a.UserName,
                a.Checked
            });
            ViewBag.ContentNum = contentList.Count;
            ViewBag.ContentList = contentList;
            return View();
        }

        public async Task<ActionResult> Group(string id)
        {
            SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_MORE, UserInfo.ID.ToString());
            var channelGroups = await _contentGroupService.List(a => true, a => a.Taxis);
            ViewBag.GroupNamesList = channelGroups;
            ViewBag.Ids = id;
            return View();
        }

        public async Task<ActionResult> Tags(string id)
        {
            SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_MORE, UserInfo.ID.ToString());
            var channelGroups = await _contentTagService.List(a => true, a => a.Id);
            ViewBag.TagsNamesList = channelGroups;
            ViewBag.Ids = id;
            return View();
        }

        public ActionResult Collating(string id)
        {
            SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_MORE, UserInfo.ID.ToString()); 
            ViewBag.Id = id;
            return View();
        }

        public ActionResult Hits(string id)
        {
            SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_MORE, UserInfo.ID.ToString());
            ViewBag.Ids = id;
            return View();
        }
        #endregion

        #region  公共方法
        [HttpGet]
        public async Task<ResponseResultDataList> GetList()
        {
            string titleType = RequestHelper.FilterParam(Request.Query["titleType"]);
            string keyword = RequestHelper.FilterParam(Request.Query["name"]);
            string channelId = RequestHelper.FilterParam(Request.Query["channelId"]);
            var containschildren = RequestHelper.FilterParam(Request.Query["containschildren"]);
            var checkedIds  = RequestHelper.FilterParam(Request.Query["checkedIds"]);
            var contentAttrIds = RequestHelper.FilterParam(Request.Query["contentAttrIds"]);
            var groupNames = RequestHelper.FilterParam(Request.Query["groupNames"]);
            var tagNames = RequestHelper.FilterParam(Request.Query["tagNames"]);

            var page = Request.Query["page"].ToString().GetQueryValueOrNull<int>(1);
            var limit = Request.Query["limit"].ToString().GetQueryValueOrNull<int>(20);
            string field = Request.Query["field"];
            string order = Request.Query["order"];

            var expable = Expressionable.Create<CmsContentEntity>();
            
            switch (titleType)
            {
                case "1"://标题
                    expable.AndIF(!string.IsNullOrEmpty(keyword), a => a.Title.Contains(keyword));
                    break;
                case "2":
                    expable.AndIF(!string.IsNullOrEmpty(keyword), a => a.SubTitle.Contains(keyword));
                    break;
                case "3":
                    expable.AndIF(!string.IsNullOrEmpty(keyword), a => a.Author.Contains(keyword));
                    break;
                case "4":
                    expable.AndIF(!string.IsNullOrEmpty(keyword), a => a.Source.Contains(keyword));
                    break;
                default:
                    expable.AndIF(!string.IsNullOrEmpty(keyword), a => a.Title.Contains(keyword));
                    break;
            }
            if (!string.IsNullOrEmpty(channelId))
            {
                if ("on" == containschildren)
                {
                    var channelModel = await _channelService.GetByIdAsync(channelId.ParseToLong());
                    string parentpath = string.IsNullOrEmpty(channelModel.ParentsPath) ? channelModel.Id.ToString() : channelModel.ParentsPath + "," + channelModel.Id.ToString();
                    expable.And(a=> parentpath.GetStringToLongArryNoNull().Contains(a.ChannelId));
                }
                else
                {
                    expable.AndIF(!string.IsNullOrEmpty(channelId), a => a.ChannelId == channelId.ParseToLong());
                }
            }
            expable.AndIF(!string.IsNullOrEmpty(checkedIds), a => checkedIds.GetStringToLongArryNoNull().Contains(a.Checked));
            if (!string.IsNullOrEmpty(contentAttrIds))
            {
                var expableAttr = Expressionable.Create<CmsContentEntity>();
                if (contentAttrIds.Contains("1")) //置顶
                {
                    expableAttr.Or(a=>a.Top==1);
                }
                if (contentAttrIds.Contains("2")) //推荐
                {
                    expableAttr.Or(a => a.Recommend == 1);
                }
                if (contentAttrIds.Contains("3")) //热点
                {
                    expableAttr.Or(a => a.Hot == 1);
                }
                if (contentAttrIds.Contains("4")) //醒目
                {
                    expableAttr.Or(a => a.Color == 1);
                }
                expable.And(expableAttr.ToExpression());
            }
            expable.AndIF(!string.IsNullOrEmpty(groupNames), a => a.GroupNameCollection.Contains(groupNames));
            expable.AndIF(!string.IsNullOrEmpty(tagNames), a => a.Tags.Contains(tagNames));

            var exp = expable.ToExpression();
            var strField = RequestHelper.FilterParam(field);
            var strOrder = RequestHelper.FilterParam(order);

            Expression<Func<CmsContentEntity, object>> expressionOrder;
            if (string.IsNullOrEmpty(strField) || string.IsNullOrEmpty(strOrder))
            {
                expressionOrder = a => new { a.CreateDate };
            }
            else
            {
                //实现字段排序
                expressionOrder = a => new { a.CreateDate };
            }
            var result = await _contentService.PageDynamicList(exp, page, limit,true, expressionOrder, a => new {
                id = a.Id,
                title = a.Title,
                top=a.Top,
                recommend = a.Recommend,
                hot=a.Hot,
                color= a.Color,
                channelId = a.ChannelId,
                createDate = a.AddTime,
                userName = a.UserName,
                checkedState = a.Checked,
            });

            return new ResponseResultDataList { code = ResponseHelper.SEUCCESSCODE, message = "请求成功", data = result.Item1, count = result.Item2 };

        }

        /// <summary>
        /// 获取筛选条件
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResponseDataResult> GetContentDropdown()
        {
            ResponseDataResult rdata = new ResponseDataResult();
            rdata.code = 0;
            rdata.message = "成功";
            rdata.data = new { checkedList =CmsHelper.GetCheckedList(), contentAttrList= GetContentAttr (), 
                groupNamesList = await GetGroupNamesList (),
                tagNamesList = await GetTagNamesList()
            };
            return rdata;
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> SaveData()
        {
            string json = string.Empty;
            using (StreamReader sr = new StreamReader(Request.Body, Encoding.UTF8))
            {
                json = sr.ReadToEndAsync().GetAwaiter().GetResult();
            }
            if (string.IsNullOrEmpty(json))
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_CSCW);
            }
            var rbodyinput = JsonSerializer.Deserialize<RequestBodyInput>(json);
            if (rbodyinput == null || string.IsNullOrEmpty(rbodyinput.ChannelId))
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_CSCW);
            }
            var channelModel = await _channelService.GetByIdAsync(rbodyinput.ChannelId.ParseToLong());
            string parentpath = string.IsNullOrEmpty(channelModel.ParentsPath) ? channelModel.Id.ToString() : channelModel.ParentsPath + "," + channelModel.Id.ToString();
            var tablestylelist = await _tablestyleService.List(a => parentpath.GetStringToLongArryNoNull().Contains(a.RelatedIdentity.Value), a => a.Taxis);
            List<string> extendList = new List<string>();
            foreach (var item in tablestylelist)
            {
                extendList.Add(item.AttributeName);
            }

            ContentInput cinput = new ContentInput();
            CmsContentEntity centity = new CmsContentEntity();
            CommonMethodHelper.GetContenxt(cinput, centity, JsonNode.Parse(json), extendList);
            bool power = true;
            long result = 0;
            //验证脏字
            var sysinfomodel = await SysInfoModelCache();
            if (sysinfomodel.BadWord=="1")
            {
                var bodylist = TextSearchProvider.Instance.FindAll(centity.Body);
                if (bodylist.Count > 0)
                {
                    return ResponseHelper.MessageResult($"内容正文包含脏字:{string.Join(',', bodylist)}");
                }
                var summarylist = TextSearchProvider.Instance.FindAll(centity.Summary);
                if (summarylist.Count > 0)
                {
                    return ResponseHelper.MessageResult($"内容摘要包含脏字:{string.Join(',', summarylist)}");
                }
            }
            
            if (centity.Id > 0)
            {
                power = SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString(), false);
                if (!power)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
                }
                var editmodel = await _contentService.GetByIdAsync(centity.Id);
                CommonMethodHelper.MapperToModel(editmodel, centity, null);
                result = await _contentService.UpdateAsync(editmodel);
            }
            else
            {
                power = SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_ADD, UserInfo.ID.ToString(), false);
                if (!power)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
                }
                centity.UserName = UserInfo.UserName;
                //查询排序值
                int taxis = await _contentService.GetTaxis(centity.ChannelId);
                centity.Taxis = taxis;
                result = await _contentService.InsertAsync(centity);
            }
            return ResponseHelper.SaveResult(result);
        }

        [HttpPost]
        public async Task<ResponseResult> Delete([FromBody] DeletDataInput input)
        {
            var r = SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_DELETE, UserInfo.ID.ToString(), false);
            if (!r)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_WSCQX);
            }
            if (string.IsNullOrEmpty(input.Ids))
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_CSCW);
            }
            int result = await _contentService.DeleteAsync(input.Ids.ToString());
            return ResponseHelper.DeleteResult(result);
        }


        /// <summary>
        /// 设置内容属性
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> SettingAttr([FromBody] ContentAttrInput input)
        {
            if (input == null || input.ContentIds.Count() == 0)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_CSCW);
            }
            var r = SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_ATTRIBUTES, UserInfo.ID.ToString(), false);
            if (!r)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
            }
           
            foreach (var contentId in input.ContentIds)
            {
               await  _contentService.SetAttr(contentId, input.Top, input.Recommend, input.Hot, input.Color,input.AttrType);
            }
            return ResponseHelper.OperateResult(1);
        }

        /// <summary>
        /// 内容调整顺序
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> SettingTaxis([FromBody] ContentTaxisInput input)
        {
            if (input == null || input.ContentIds.Count() == 0)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_CSCW);
            }
            var r = SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_TAXIS, UserInfo.ID.ToString(), false);
            if (!r)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
            }
            var expendedChannelIds = new List<long>();

            if (input.IsUp == 0)
            {
                input.ContentIds.Reverse();
            }
            foreach (var contentId in input.ContentIds)
            {
                var content = await _contentService.GetByIdAsync(contentId);
                if (content == null) continue;
                var isTop = content.Top;
                for (var i = 1; i <= input.Taxis; i++)
                {
                    if (input.IsUp==1)
                    {
                        if (await _contentService.SetTaxisToUp(content.ChannelId, content.Id, isTop) == 0)
                        {
                            break;
                        }
                    }
                    else
                    {
                        if (await _contentService.SetTaxisToDown(content.ChannelId, content.Id, isTop) == 0)
                        {
                            break;
                        }
                    }
                }
            }
            return ResponseHelper.OperateResult(1);
        }


        /// <summary>
        /// 内容转移
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> SetTranslate([FromBody] ContentTranslateInput input)
        {
            if (input == null || input.ContentIds.Count() == 0)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_CSCW);
            }
            var r = SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_COPY, UserInfo.ID.ToString(), false);
            if (!r)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
            }

            input.ContentIds.Reverse();
            foreach (var contentId in input.ContentIds)
            {
                var model = await _contentService.GetByIdAsync(contentId);
                await TranslateChannelContent(model.ChannelId, model.Id, input.TargetChannelId,input.IsDeleteAfterTranslate);
            }
         
            return ResponseHelper.OperateResult(1);
        }

        /// <summary>
        /// 设置内容分组
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> SettingGroup([FromBody] ContentGroupInput input)
        {
            if (input == null || input.ContentIds.Count() == 0)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_CSCW);
            }

            var r = SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_MORE, UserInfo.ID.ToString(), false);
            if (!r)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
            }
            var contentGroupList = await _contentGroupService.List(a => true, a => a.Taxis);
            if (contentGroupList == null || contentGroupList.Count == 0)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_CSCW);
            }
            var allGroupNames = contentGroupList.Select(a => a.GroupName).ToList();
            foreach (var contentId in input.ContentIds)
            {
                var content = await _contentService.GetByIdAsync(contentId);
                if (content == null) continue;

                var list = new List<string>();
                foreach (var groupNames in CommonUtil.GetStringList(content.GroupNameCollection))
                {
                    if (allGroupNames.Contains(groupNames))
                    {
                        list.Add(groupNames);
                    }
                }

                foreach (var name in input.GroupNames)
                {
                    if (input.GroupType == 0)
                    {
                        if (list.Contains(name)) list.Remove(name);
                    }
                    else
                    {
                        if (!list.Contains(name)) list.Add(name);
                    }
                }
                content.GroupNameCollection = string.Join(",", list);

                await _contentService.UpdateAsync(content);
            }
            return ResponseHelper.OperateResult(1);
        }

        /// <summary>
        /// 设置标签分组
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> SettingTag([FromBody] ContentSettingTagInput input)
        {
            if (input == null || input.ContentIds.Count() == 0)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_CSCW);
            }

            var r = SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_MORE, UserInfo.ID.ToString(), false);
            if (!r)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
            }
            var contentTagList = await _contentTagService.List(a => true, a => a.Id);
            if (contentTagList == null || contentTagList.Count == 0)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_CSCW);
            }
            var alltagNames = contentTagList.Select(a => a.TagName).ToList();
            foreach (var contentId in input.ContentIds)
            {
                var content = await _contentService.GetByIdAsync(contentId);
                if (content == null) continue;

                var list = new List<string>();
                foreach (var tagNames in CommonUtil.GetStringList(content.Tags))
                {
                    if (alltagNames.Contains(tagNames))
                    {
                        list.Add(tagNames);
                    }
                }

                foreach (var name in input.TagNames)
                {
                    if (input.TagType == 0)
                    {
                        if (list.Contains(name)) list.Remove(name);
                    }
                    else
                    {
                        if (!list.Contains(name)) list.Add(name);
                    }
                }
                content.Tags = string.Join(",", list);

                await _contentService.UpdateAsync(content);
            }
            return ResponseHelper.OperateResult(1);
        }

        /// <summary>
        /// 内容整理排序
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> SettingArrange([FromBody] ContentArrangeInput input)
        {
            if (input == null || input.ChannelId==0)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_CSCW);
            }

            var r = SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_MORE, UserInfo.ID.ToString(), false);
            if (!r)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
            }
            var channel = await _channelService.GetByIdAsync(input.ChannelId);
            if (channel == null) return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_WFQDNRDYDLM);

            await _contentService.SetArrangeTaxis(channel.Id, input.AttributeName, input.IsDesc);

            return ResponseHelper.OperateResult(1);
        }

        /// <summary>
        /// 设置点击量
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> SettingHits([FromBody] ContentHitsInput input)
        {
            if (input == null || input.ContentIds.Count() == 0)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_CSCW);
            }

            var r = SysPower(SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.FUN_MORE, UserInfo.ID.ToString(), false);
            if (!r)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
            }

            foreach (var contentId in input.ContentIds)
            {
                await _contentService.SetHits(contentId, input.Hits, input.IsAdd);
            }
            return ResponseHelper.OperateResult(1);
        }

        #endregion


        #region 私有方法
        /// <summary>
        /// 内容属性
        /// </summary>
        /// <returns></returns>
        private List<CheckedItemModel> GetContentAttr()
        {
            List<CheckedItemModel> hashtables = new List<CheckedItemModel>();
            hashtables.Add(new CheckedItemModel
            {
                Id = "1",
                Title = "置顶"
            });
            hashtables.Add(new CheckedItemModel
            {
                Id = "2",
                Title = "推荐"
            });
            hashtables.Add(new CheckedItemModel
            {
                Id = "3",
                Title = "热点"
            });
            hashtables.Add(new CheckedItemModel
            {
                Id = "4",
                Title = "醒目"
            });
            return hashtables;
        }

        /// <summary>
        /// 内容组
        /// </summary>
        /// <returns></returns>
        private async  Task<List<CheckedItemModel>> GetGroupNamesList()
        {
            List<CheckedItemModel> hashtables = new List<CheckedItemModel>();
            var contentGroups = await _contentGroupService.List(a => true, a => a.Taxis);
            foreach (var item in contentGroups)
            {
                var model = new CheckedItemModel { 
                  Id  =item.Id.ToString(),
                  Title  = item.GroupName,
                  IsChecked = 0
                };
                hashtables.Add(model);
            }
            return  hashtables;
        }
        /// <summary>
        /// 标签
        /// </summary>
        /// <returns></returns>
        private async Task<List<CheckedItemModel>> GetTagNamesList()
        {
            List<CheckedItemModel> hashtables = new List<CheckedItemModel>();
            var contentTags = await _contentTagService.List(a => true, a => a.UseNum);
          
            foreach (var item in contentTags)
            {
                var model = new CheckedItemModel
                {
                    Id = item.Id.ToString(),
                    Title = item.TagName,
                    IsChecked = 0
                };
              
                hashtables.Add(model);
            }
            
            return hashtables;
        }

        
        private async Task TranslateChannelContent(long channelId, long contentId, long targetChannelId,int translateType)
        {
            if (channelId <= 0 || contentId <= 0 || targetChannelId <= 0) return;

            var contentInfo = await _contentService.GetByIdAsync(contentId);

            if (contentInfo == null) return;

            if (translateType == 0)
            {
                CmsContentEntity newContent = new CmsContentEntity();
                CommonMethodHelper.MapperToModel(newContent, contentInfo, null);
                newContent.ChannelId = targetChannelId;
                newContent.Taxis = 0;
                newContent.Id = 0;
                var theContentId = await _contentService.InsertAsync(newContent);

                //如果有审核直接复制审核记录
                var contentCheckList = await _contentCheckService.GetContentCheck(channelId, contentId);
                foreach (var item in contentCheckList)
                {
                    CmsContentCheckEntity newContentCheck = new CmsContentCheckEntity();
                    CommonMethodHelper.MapperToModel(newContentCheck, item, null);
                    newContentCheck.ChannelId = targetChannelId;
                    newContentCheck.ContentId = theContentId;
                    newContentCheck.Id = 0;
                    //item.ChannelId = targetChannelId;
                    //item.ContentId = theContentId;
                    await _contentCheckService.InsertAsync(newContentCheck);
                }
            }
            else if (translateType == 1)
            {
                contentInfo.ChannelId = targetChannelId;
                contentInfo.Taxis = 0;
                await _contentService.UpdateAsync(contentInfo);
            }
        }
        #endregion
    }
}